/**
 * 用户Store
 */
import { defineStore } from 'pinia'
import { ref } from 'vue'
import { login as loginApi, getUserInfo as getUserInfoApi, logout as logoutApi } from '@/api/auth'
import router from '@/router'

export const useUserStore = defineStore('user', () => {
  // 用户信息
  const userInfo = ref(null)
  // Token
  const accessToken = ref(localStorage.getItem('admin_access_token') || '')
  const refreshToken = ref(localStorage.getItem('admin_refresh_token') || '')
  // 权限菜单
  const menus = ref([])
  // 权限代码
  const permissions = ref([])

  /**
   * 登录
   */
  const login = async (username, password) => {
    try {
      const res = await loginApi({ username, password })
      const { access_token, refresh_token, user_info } = res.data
      
      // 保存Token
      accessToken.value = access_token
      refreshToken.value = refresh_token
      localStorage.setItem('admin_access_token', access_token)
      localStorage.setItem('admin_refresh_token', refresh_token)
      
      // 保存用户信息
      userInfo.value = user_info
      localStorage.setItem('admin_user_info', JSON.stringify(user_info))
      
      return true
    } catch (error) {
      console.error('Login failed:', error)
      return false
    }
  }

  /**
   * 获取用户信息（包含菜单和权限）
   */
  const getUserInfo = async () => {
    try {
      const res = await getUserInfoApi()
      userInfo.value = res.data
      menus.value = res.data.menus || []
      permissions.value = res.data.permissions || []
      
      localStorage.setItem('admin_user_info', JSON.stringify(res.data))
      return true
    } catch (error) {
      console.error('Get user info failed:', error)
      return false
    }
  }

  /**
   * 登出
   */
  const logout = async () => {
    try {
      await logoutApi()
    } catch (error) {
      console.error('Logout failed:', error)
    } finally {
      // 清除本地数据
      accessToken.value = ''
      refreshToken.value = ''
      userInfo.value = null
      menus.value = []
      permissions.value = []
      
      localStorage.removeItem('admin_access_token')
      localStorage.removeItem('admin_refresh_token')
      localStorage.removeItem('admin_user_info')
      
      router.push('/login')
    }
  }

  /**
   * 检查是否有某个权限
   */
  const hasPermission = (permissionCode) => {
    // 超级管理员拥有所有权限
    if (userInfo.value?.role?.code === 'super_admin') {
      return true
    }
    return permissions.value.includes(permissionCode)
  }

  /**
   * 初始化用户信息（从localStorage恢复）
   */
  const initUserInfo = () => {
    const storedUserInfo = localStorage.getItem('admin_user_info')
    if (storedUserInfo) {
      try {
        const parsed = JSON.parse(storedUserInfo)
        userInfo.value = parsed
        menus.value = parsed.menus || []
        permissions.value = parsed.permissions || []
      } catch (error) {
        console.error('Parse user info failed:', error)
      }
    }
  }

  return {
    userInfo,
    accessToken,
    refreshToken,
    menus,
    permissions,
    login,
    getUserInfo,
    logout,
    hasPermission,
    initUserInfo
  }
})

